package rpc

import (
	"context"
	"fmt"
	proto "go-graduation/pb/router"
	"go-graduation/service/internal/biz"
	"google.golang.org/grpc"
	"google.golang.org/grpc/reflection"
	"log"
	"net"
)

type GrpcServer struct {
	port string
}

func (s *GrpcServer) ArticleDetail(ctx context.Context, in *proto.ArticleDetailRequest) (*proto.ArticleDetailResponse, error) {
	resp := biz.GetOneArticleById(ctx, in)
	return &resp, nil
}

func (s *GrpcServer) ArticleList(ctx context.Context, in *proto.ArticleListRequest) (*proto.ArticleListResponse, error) {
	resp := biz.GetArticleByPage(ctx, in)
	return &resp, nil
}

func (s *GrpcServer) ArticleCommentList(ctx context.Context, in *proto.ArticleCommentListRequest) (*proto.ArticleCommentListResponse, error) {
	resp := biz.GetArticleCommentByPage(ctx, in)
	return &resp, nil
}

func (s *GrpcServer) ArticleCommentAdd(ctx context.Context, in *proto.ArticleCommentAddRequest) (*proto.ArticleCommentAddResponse, error) {
	resp := biz.AddComment(ctx, in)
	return &resp, nil
}

func GrpcServerStart(port string) {
	lis, err := net.Listen("tcp", port)
	if err != nil {
		fmt.Printf("failed to listen: %v", err)
		return
	}

	s := grpc.NewServer()
	proto.RegisterArticleListServiceServer(s, &GrpcServer{})
	proto.RegisterArticleDetailServiceServer(s, &GrpcServer{})
	proto.RegisterArticleCommentAddServiceServer(s, &GrpcServer{})
	proto.RegisterArticleCommentListServiceServer(s, &GrpcServer{})

	defer func() {
		s.Stop()
		lis.Close()
	}()

	fmt.Println("Serving " + port + "...")
	// https://github.com/grpc/grpc-go/blob/master/Documentation/server-reflection-tutorial.md
	reflection.Register(s)
	if err := s.Serve(lis); err != nil {
		log.Fatalf("failed to serve: %v", err)
	}
}
